﻿//////////////////////////////////////////////////////////////////////////////////
//
// Project            : SilverlightAsyncSave
// Module             : SilverlightAsyncSave
// Description        : Home page.
// 
// Repository         : $URL$
// Last changed by    : $LastChangedBy$
// Revision           : $LastChangedRevision$
// Last Changed       : $LastChangedDate$
// Author             : $Author$
//
// Id                 : $Id$
//
// Copyright          : (c) 2010 Torsten Bär
//
// Published under the MIT License. See license.txt or http://www.opensource.org/licenses/mit-license.php.
//
//////////////////////////////////////////////////////////////////////////////////
using System;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using SilverlightAsyncSave.FileService;

namespace SilverlightAsyncSave
{
   /// <summary>
   /// Home page.
   /// </summary>
   public partial class Home : Page
   {
      /// <summary>
      /// Gets or sets the view model.
      /// </summary>
      /// <value>The view model.</value>
      private ViewModel ViewModel { get; set; }

      /// <summary>
      /// Gets or sets the content of the file.
      /// </summary>
      /// <value>The content of the file.</value>
      protected string FileContent { get; set; }

      /// <summary>
      /// Gets or sets a value indicating whether this instance is data available.
      /// </summary>
      /// <value>
      /// 	<c>true</c> if this instance is data available; otherwise, <c>false</c>.
      /// </value>
      protected bool IsDataAvailable { get; set; }

      /// <summary>
      /// Initializes a new instance of the <see cref="Home"/> class.
      /// </summary>
      public Home()
      {
         InitializeComponent();

         ViewModel = new ViewModel();
         DataContext = ViewModel;
      }

      // Executes when the user navigates to this page.
      /// <summary>
      /// Called when a page becomes the active page in a frame.
      /// </summary>
      /// <param name="e">An object that contains the event data.</param>
      protected override void OnNavigatedTo(NavigationEventArgs e)
      {
         FileServiceClient client = new FileServiceClient();
         client.GetFilesCompleted += (s, evtArgs) =>
                                     {
                                        ViewModel.FileItems = evtArgs.Result;
                                        IsDataAvailable = true;
                                     };
         client.GetFilesAsync();
      }

      /// <summary>
      /// Handles the Click event of the SaveSync control.
      /// </summary>
      /// <param name="sender">The source of the event.</param>
      /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
      private void SaveSync_Click(object sender, RoutedEventArgs e)
      {
         FileNameSync.Text = String.Empty;
         if (!IsDataAvailable)
            return;

         // Step 1
         // Load file content
         if (FileContent == null)
         {
            if (ViewModel.SelectedFile != null)
            {
               var client = new FileServiceClient();
               client.GetFileContentCompleted += (s, evtArgs) =>
                                                 {
                                                    FileContent = evtArgs.Result;
                                                 };
               client.GetFileContentAsync(ViewModel.SelectedFile);
            }

            FileNameSync.Text = "prepared";
            return;
         }
         
         // Step 2
         // Save data
         SaveFileDialog saveFileDialog = new SaveFileDialog();
         if (saveFileDialog.ShowDialog() == true)
         {
            using (var stream = saveFileDialog.OpenFile())
            {
               using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
               {
                  writer.Write(FileContent);
                  FileNameSync.Text = saveFileDialog.SafeFileName;
               }
            }
         }
         FileContent = null;
      }

      /// <summary>
      /// Handles the Click event of the SaveAsync control.
      /// </summary>
      /// <param name="sender">The source of the event.</param>
      /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
      private void SaveAsync_Click(object sender, RoutedEventArgs e)
      {
         // open dialog
         SaveFileDialog saveFileDialog = new SaveFileDialog();
         Stream stream = null;
         if (saveFileDialog.ShowDialog() == true)
         {
            FileNameAsync.Text = saveFileDialog.SafeFileName;
            stream = saveFileDialog.OpenFile();
         }

         // get and save data
         var client = new FileServiceClient();
         client.GetFileContentCompleted += (s, evtArgs) =>
         {
            using (stream)
            {
               using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
               {
                  writer.Write(evtArgs.Result);
               }
            }
         };
         client.GetFileContentAsync(ViewModel.SelectedFile);
      }
   }
}